var PublicFun = require('../../../Base/server/controllers/Function'),
    PublicEnum = require('../../../Base/server/controllers/Enum'),
    Transaction = require('../../../Base/server/controllers/Transaction'),
    QCEnum = require('../../../QC/server/controllers/Enum.server.controller'),
    BarcodeEnum = require('../../../Barcode/server/controllers/Enum.server.controller'),

    userController = require('../../../User/server/controllers/users.server.controller'),
    operationController = require('../../../CBO/server/controllers/Operation.server.controller'),
    terminalController = require('../../../CBO/server/controllers/Terminal.server.controller'),
    stationWorkController = require('../../../Initialize/server/controllers/StationWork.server.controller'),
    barcodeMasterController = require('../../../Barcode/server/controllers/BarcodeMaster.server.controller'),
    bizRecordController = require('../../../Barcode/server/controllers/BizRecord.server.controller'),
    qcRecordController = require('../../../QC/server/controllers/QCRecord.server.controller'),
    qcStandardController = require('../../../QC/server/controllers/QCStandard.server.controller'),
    badTypeBindController = require('../../../QC/server/controllers/BadTypeBind.server.controller'),
    extendEnumController = require('../../../SystemManage/server/controllers/ExtendEnum.server.controller');

//根据终端UniqueID获取终端、工位、作业集合
exports.getTerminalWorkLocationWorks = function (req, res) {
    //PublicFun.authorizedCheck(req.user, res);
    var parameter = req.body.Parameter;
    var terminalUniqueID = parameter.TerminalUniqueID;

    var returnData = {
        Terminal: null,
        WorkLocation: null,
        Works: []
    }

    //查找终端
    terminalController.findByUniqueID(terminalUniqueID, function (err, terminalRecord) {
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
        }
        else {
            if (terminalRecord == null) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询终端错误';
                newErr.message = '请检查查询参数！';
                res.json({
                    Data: null,
                    Error: newErr
                });
            }
            else {
                returnData.Terminal = terminalRecord;
                stationWorkController.getStationWorksByTerminalID(terminalRecord._id, function (err, stationWorkRecords) {
                    if (err) {
                        res.json({
                            Data: null,
                            Error: err
                        });
                    }
                    else {
                        if (stationWorkRecords.length > 0) {
                            returnData.WorkLocation = stationWorkRecords[0].WorkLocation;
                        }
                        for (var i = 0; i < stationWorkRecords.length; i++) {
                            returnData.Works.push(stationWorkRecords[i].Work);
                        }
                        res.json({
                            Data: returnData,
                            Error: null
                        });
                    }
                });
            }
        }
    });
};

//根据条码和作业获取默人或物的信息
exports.getFirstQCDefaultInfo = function (req, res) {
    //PublicFun.authorizedCheck(req.user, res);
    var self = this;
    var parameter = req.body.Parameter;
    var workId = parameter.WorkID;			//查询流水信息使用
    var barcode = parameter.Barcode;

    barcodeMasterController.findBarcodeMaster(barcode, function (err, barcodeMasterRecord) {
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
        }
        else {
            if (barcodeMasterRecord == null) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '条码扫描失败';
                newErr.message = '该条码没有对应的条码主档！';
                res.json({
                    Data: null,
                    Error: newErr
                });
            }
            else {
                if (barcodeMasterRecord.BarcodeType == BarcodeEnum.BarcodeType.ItemMaster) {
                    self.findFirstQCInfo(barcodeMasterRecord, workId, function (err, data) {
                        res.json({
                            Data: data,
                            Error: err
                        });
                    });
                }
                else if (barcodeMasterRecord.BarcodeType == BarcodeEnum.BarcodeType.Person) {
                    userController.getUserAndRolesInfo(barcodeMasterRecord.EntityID, function (err, userRecord) {
                        if (err) {
                            res.json({
                                Data: null,
                                Error: err
                            });
                        }
                        else {
                            if (userRecord == null) {
                                var newErr = new Error();
                                newErr.leval = 9;
                                newErr.title = '查找员工档失败';
                                newErr.message = '该条码没有对应的员工信息！';
                                res.json({
                                    Data: null,
                                    Error: newErr
                                });
                            }
                            else {
                                delete userRecord._doc.Password;
                                delete userRecord._doc.Image;
                                delete userRecord._doc.Salt;
                                delete userRecord._doc.ResetPasswordToken;
                                delete userRecord._doc.ResetPasswordExpires;
                                res.json({
                                    Data: {User: userRecord},
                                    Error: null
                                });
                            }
                        }
                    });
                }
                else {
                    var newErr = new Error();
                    newErr.leval = 9;
                    newErr.title = '条码扫描失败';
                    newErr.message = '该条码对应的不是员工或者物料！';
                    res.json({
                        Data: null,
                        Error: err
                    });
                }
            }
        }
    });
};

//提交首件质检信息
exports.setFirstQCInfo = function (req, res) {
    var parameter = req.body.Parameter;
    if (parameter == null || parameter == undefined) {
        var newErr = new Error();
        newErr.leval = 9;
        newErr.title = '参数传入错误';
        newErr.message = 'Parameter值没有';

        res.json({
            Data: null,
            Error: newErr
        });
    }

    var user = parameter.User,
        terminal = parameter.Terminal,
        workLocation = parameter.WorkLocation,
        work = parameter.Work,

        barcodeMaster = parameter.BarcodeMaster,
        bizRecord = parameter.BizRecord,
        qcRecords = parameter.QCRecords;

    //修改条码主档
    var barcodeMasterData = {
        _id: barcodeMaster._id,
        RowStatus: PublicEnum.RowStatus.Modify,
        ModifyBy: user._id,

        BizRecord: null,
        Operation: null,
        OperationName: null,
        Work: work._id,
        WorkName: work.Name,
        WorkLocation: workLocation._id,
        WorkLocationName: workLocation.Name,
        Terminal: terminal._id,
        TerminalName: terminal.Name,
        QCType: QCEnum.QCType.FirstQuality,
        Users: [user._id]
    };

    //根据物料和作业查找工序
    operationController.findByItemMasterAndWork(barcodeMaster.ItemMaster._id, work._id, function (err, operationRecord) {
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
        }
        else {
            if (operationRecord == null) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询工序失败';
                newErr.message = '该物料没有找到对应作业的工序！';
                res.json({
                    Data: null,
                    Error: newErr
                });
            }
            else {
                barcodeMasterData.Operation = operationRecord._id;
                barcodeMasterData.OperationName = operationRecord.Name;

                //创建条码流水数据
                var bizRecordData = {
                    BarcodeMaster: barcodeMaster._id,

                    Terminal: terminal._id,
                    TerminalName: terminal.Name,
                    Operation: operationRecord._id,
                    OperationName: operationRecord.Name,
                    Work: work._id,
                    WorkName: work.Name,

                    WorkLocation: workLocation._id,
                    WorkLocationName: workLocation.Name,
                    BusinessStatus: null,
                    QCType: QCEnum.QCType.FirstQuality,
                    Remark: bizRecord.Remark
                };
                if (user.IsQC) {
                    bizRecordData.QCUser = user._id;
                    bizRecordData.QCDateTime = new Date();
                    bizRecordData.BusinessStatus = BarcodeEnum.BusinessStatus.Complete;
                }
                else {
                    bizRecordData.Users = [user._id];
                    bizRecordData.CollectDateTime = new Date();
                    bizRecordData.BusinessStatus = BarcodeEnum.BusinessStatus.Start;
                }

                if (bizRecord._id == null || bizRecord._id == undefined) {
                    bizRecordData.RowStatus = PublicEnum.RowStatus.Insert;
                    bizRecordData.CreatedBy = user._id;
                }
                else {
                    barcodeMasterData.BizRecord = bizRecord._id;
                    bizRecordData._id = bizRecord._id;
                    bizRecordData.RowStatus = PublicEnum.RowStatus.Modify;
                    bizRecordData.ModifyBy = user._id;
                }

                //创建品质记录
                var qcRecordDatas = [];
                var isQualified = true;
                for (var i = 0; i < qcRecords.length; i++) {
                    var qcRecordData = {
                        BizRecord: null,
                        QCNorm: qcRecords[i].QCNorm._id,
                        QCStandard: qcRecords[i].QCStandard._id,
                        NormValue: qcRecords[i].NormValue,
                        IsQualified: qcRecords[i].IsQualified
                    };
                    if (bizRecord._id == null || bizRecord._id == undefined) {
                        qcRecordData.RowStatus = PublicEnum.RowStatus.Insert;
                        qcRecordData.CreatedBy = user._id;
                    }
                    else {
                        qcRecordData._id = qcRecords[i]._id;
                        qcRecordData.RowStatus = PublicEnum.RowStatus.Modify;
                        qcRecordData.ModifyBy = user._id;
                        qcRecordData.BizRecord = bizRecord._id;
                    }
                    if (qcRecords[i].IsQualified == false ||
                        qcRecords[i].IsQualified == null ||
                        qcRecords[i].IsQualified == undefined) {
                        isQualified = false;
                    }
                    qcRecordDatas.push(qcRecordData);
                }
                if (isQualified) {
                    bizRecordData.QCStatus = QCEnum.QCStatus.Qualified;
                }
                else {
                    bizRecordData.QCStatus = QCEnum.QCStatus.NotQualified;
                }

                if (bizRecordData.RowStatus == PublicEnum.RowStatus.Insert) {
                    delete bizRecordData.RowStatus;
                    //提交条码流水
                    bizRecordController.insert(bizRecordData, function (err, newBizRecord) {
                        if (err) {
                            res.json({
                                Data: null,
                                Error: err
                            });
                        }
                        else {
                            barcodeMasterData.BizRecord = newBizRecord._id;
                            for (var i = 0; i < qcRecordDatas.length; i++) {
                                qcRecordDatas[i].BizRecord = newBizRecord._id;
                            }

                            //提交品质记录与条码主档
                            Transaction.BatchSaveByTran(
                                [
                                    {EntityName: 'QCRecord', Records: qcRecordDatas},
                                    {EntityName: 'BarcodeMaster', Records: [barcodeMasterData]}
                                ],
                                function (err, result) {
                                    if (err) {
                                        bizRecordController.deleteById(newBizRecord._id, function (err, deleteResult) {
                                        });
                                        res.json({
                                            Data: null,
                                            Error: err
                                        });
                                    }
                                    else {
                                        res.json({
                                            Data: true,
                                            Error: null
                                        });
                                    }
                                }
                            );
                        }
                    });
                }
                else {
                    Transaction.BatchSaveByTran(
                        [
                            {EntityName: 'BarcodeMaster', Records: [barcodeMasterData]},
                            {EntityName: 'BizRecord', Records: [bizRecordData]},
                            {EntityName: 'QCRecord', Records: qcRecordDatas}
                        ],
                        function (err, result) {
                            if (err) {
                                res.json({
                                    Data: null,
                                    Error: err
                                });
                            }
                            else {
                                res.json({
                                    Data: true,
                                    Error: null
                                });
                            }
                        }
                    );
                }
            }
        }
    });
};

//根据条码主档记录和作业ID查找首件质检信息
exports.findFirstQCInfo = function (barcodeMaster, workId, completeFun) {
    var returnData = {
        BarcodeMaster: null,
        BizRecord: {
            _id: null,
            User: null,
            CollectDateTime: null,
            QCUser: null,
            QCDateTime: null,
            Remark: null
        },
        QCRecords: []
    };

    returnData.BarcodeMaster = {
        _id: barcodeMaster._id,
        MO: null,
        ItemMaster: null,
        Work: null
    };

    if (barcodeMaster.Work != null) {
        returnData.BarcodeMaster.Work = {
            _id: barcodeMaster.Work._id,
            Name: barcodeMaster.Work.Name
        }
    }
    if (barcodeMaster.MO != null) {
        returnData.BarcodeMaster.MO = {
            _id: barcodeMaster.MO._id, 				//MO ID
            Code: barcodeMaster.MO.Code,				//单号
            LotNumber: barcodeMaster.MO.LotNumber		//批次
        };
    }
    if (barcodeMaster.ItemMaster != null) {
        returnData.BarcodeMaster.ItemMaster = {
            _id: barcodeMaster.ItemMaster._id,		//料品ID
            Code: barcodeMaster.ItemMaster.Code,	//料号
            Name: barcodeMaster.ItemMaster.Name,	//品名
            Specification: barcodeMaster.ItemMaster.Specification	//规格/型号
        }
    }

    //查找条码流水
    bizRecordController.findByBarcodeMasterAndWork(barcodeMaster._id, workId, function (err, bizRecord) {
        if (err) {
            completeFun(err);
        }
        else {
            if (bizRecord == null) {
                //查找检验标准
                qcStandardController.findQCStandard(barcodeMaster.ItemMaster._id, workId, function (err, standardRecords) {
                    if (err) {
                        completeFun(err);
                    }
                    else {
                        for (var i = 0; i < standardRecords.length; i++) {
                            var enumValues = null;
                            if (standardRecords[i].QCNorm.ExtendEnum != null && standardRecords[i].QCNorm.ExtendEnum != undefined) {
                                enumValues = standardRecords[i].QCNorm.ExtendEnum.Options;
                            }
                            returnData.QCRecords.push(
                                {
                                    _id: null,
                                    QCNorm: {
                                        _id: standardRecords[i].QCNorm._id,
                                        Name: standardRecords[i].QCNorm.Name,
                                        Type: standardRecords[i].QCNorm.Type,
                                        EnumValues: enumValues
                                    },
                                    QCStandard: {
                                        _id: standardRecords[i]._id,
                                        StandardValue: standardRecords[i].StandardValue,
                                        ValueUpperLimit: standardRecords[i].ValueUpperLimit,
                                        ValueLowerLimit: standardRecords[i].ValueLowerLimit
                                    },
                                    NormValue: null,
                                    IsQualified: false
                                }
                            );
                        }
                        completeFun(null, returnData);
                    }
                });
            }
            else {
                returnData.BizRecord = {
                    _id: bizRecord._id,
                    CollectDateTime: bizRecord.CollectDateTime,
                    QCUser: bizRecord.QCUser,
                    QCDateTime: bizRecord.QCDateTime,
                    Remark: bizRecord.Remark
                };

                if (bizRecord.Users != null && bizRecord.Users.length > 0) {
                    returnData.BizRecord.User = bizRecord.Users[0]
                }

                //查找品质记录
                qcRecordController.findQCRecordByBizRecordID(bizRecord._id, function (err, qcRecords) {
                    if (err) {
                        completeFun(err);
                    }
                    else {
                        var findExendEnumCount = 0;
                        for (var i = 0; i < qcRecords.length; i++) {
                            var enumValues = null;
                            if (qcRecords[i].QCNorm.ExtendEnum != null && qcRecords[i].QCNorm.ExtendEnum != undefined) {
                                enumValues = qcRecords[i].QCNorm.ExtendEnum.Options;
                            }
                            returnData.QCRecords.push(
                                {
                                    _id: qcRecords[i]._id,
                                    QCNorm: {
                                        _id: qcRecords[i].QCNorm._id,
                                        Name: qcRecords[i].QCNorm.Name,
                                        Type: qcRecords[i].QCNorm.Type,
                                        EnumValues: enumValues
                                    },
                                    QCStandard: {
                                        _id: qcRecords[i].QCStandard._id,
                                        StandardValue: qcRecords[i].QCStandard.StandardValue,
                                        ValueUpperLimit: qcRecords[i].QCStandard.ValueUpperLimit,
                                        ValueLowerLimit: qcRecords[i].QCStandard.ValueLowerLimit
                                    },
                                    NormValue: qcRecords[i].NormValue,
                                    IsQualified: qcRecords[i].IsQualified
                                }
                            );
                        }
                        completeFun(null, returnData);
                    }
                });
            }
        }
    });
};

// 根据物料和作业获取缺陷类型
exports.getBadType = function (req, res) {
    var parameter = req.body.Parameter,
        itemMasterId = parameter.ItemMasterId,
        workId = parameter.WorkId;
    qcStandardController.findQCStandard(itemMasterId, workId, function (err, standardRecords) {
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
            return;
        }
        if (!standardRecords || standardRecords.length == 0) {
            res.json({
                Data: [],
                Error: null
            });
        }
        var qcNormIds = [];
        for (var i = 0; i < standardRecords.length; i++) {
            qcNormIds.push(standardRecords[i].QCNorm._id);
        }
        badTypeBindController.findBadTypeByQCNormID(qcNormIds, function (err, badTypeRecords) {
            if (err) {
                res.json({
                    Data: null,
                    Error: err
                });
                return;
            }
            var badType = [];
            for (var i = 0; i < badTypeRecords.length; i++) {
                badType.push(badTypeRecords[i].BadType);
            }
            extendEnumController.findByCode('BadType', function (err, data) {
                if (err) {
                    res.json({
                        Data: null,
                        Error: err
                    });
                    return;
                }
                var badTypeName = [];

                for (var i = 0; i < badType.length; i++) {
                    for (var j = 0; j < data.Options.length; j++) {
                        if (data.Options[j].Value == badType[i]) {
                            badTypeName.push({
                                Value:data.Options[j].Value,
                                Name:data.Options[j].Name
                            });
                        }
                    }
                }

                res.json({
                    Data: badTypeName,
                    Error: null
                });
            });
        });
    });
};
